package com.jc.service.permission;

import java.util.*;
import java.util.stream.Collectors;

import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.RolePermission;
import com.jc.service.rolepermission.RolePermissionService;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jc.cds.mapper.CustomPermissionMapper;
import com.jc.cds.model.CustomPermission;
import com.jc.ds.base.service.BaseServiceImpl;
import com.jc.ds.model.Permission;
import org.springframework.transaction.annotation.Transactional;

@SuppressWarnings("all")
@Service
public class PermissionServiceImpl extends BaseServiceImpl<Permission, CustomPermission, Long> implements PermissionService {

	@Autowired
	private RolePermissionService rolePermissionService;

	@Override
	public CustomPermissionMapper getCustomMapper() {
		return (CustomPermissionMapper)this.getBaseCustomMapper();
	}



	public Set<String> getUserPermissionListByUserId(Long userId){
		return this.getCustomMapper().getPermissionByUserId(userId);
	}

	@Override
	public List<Permission> queryPermissionByRoleId(Long roleId) {
		List<Map<String,Object>> resultMap = new ArrayList<>();
		//查询所有的菜单和按钮
		List<Permission> permissions = this.queryAll(new Permission());
		//查询用户的所有权限
		List<RolePermission> rolePermissions = rolePermissionService.queryAll(new RolePermission() {{
			setRoleId(roleId);
		}});
		List<Permission> buttons = new ArrayList<>();
		List<Permission> menus = new ArrayList<>();
		for (Permission permission : permissions){
			if (permission.getPermissionType() == 0){
				buttons.add(permission);
			}else{
				menus.add(permission);
			}
		}
		for (Permission menu:menus){
			List<Permission> per = new ArrayList<>();
			for (Permission button:buttons) {
				if (menu.getId() == button.getParentId()){
					for (RolePermission rolePermission : rolePermissions){
						if (rolePermission.getPermissionId().toString().equals(button.getId().toString())){
							System.out.println("id ======"+ rolePermission.getPermissionId());
							button.setChecked(true);
						}
					}
					per.add(button);
				}
			}
			menu.setButtonList(per);
		}
		List<Long> menuIds = new ArrayList<>();
		for (RolePermission rolePermission:rolePermissions) {
			menuIds.add(rolePermission.getPermissionId());
		}
		//根节点
		List<Permission> rootMenu = new ArrayList<Permission>();
		for (Permission nav : menus) {
			if(nav.getParentId().toString().equals("0")){//父节点是0的，为根节点。
				rootMenu.add(nav);
			}
		}
		/* 根据Menu类的order排序 */
		Collections.sort(rootMenu, order());
		//为根菜单设置子菜单，getClild是递归调用的
		for (Permission nav : rootMenu) {
			/* 获取根节点下的所有子节点 使用getChild方法*/
			Map<String, List<Permission>> child = getChild(nav.getId(), menus, menuIds);
			nav.setChildren(child.get("menuList"));//给根节点设置子节点
		}
		return rootMenu;
	}

	@Transactional
	@Override
	public Boolean updateRolePermission(String roleId, String permissionId, String isChecked) {
		//查询用户是否有次权限
		List<RolePermission> rolePermissions = rolePermissionService.queryAll(new RolePermission() {{
			setRoleId(Long.valueOf(roleId));
			setPermissionId(Long.valueOf(permissionId));
		}});
		if (CollectionUtils.isNotEmpty(rolePermissions) && Boolean.valueOf(isChecked))throw new BaseServiceException("用户已经有此权限，无须重复操作!");

		if (Boolean.valueOf(isChecked)){
			//新增
			rolePermissionService.add(new RolePermission(){{
				setPermissionId(Long.valueOf(permissionId));
				setRoleId(Long.valueOf(roleId));
			}},false);
			//查询是否有父级权限
			Permission permission = this.queryById(Long.valueOf(permissionId));
			List<RolePermission> rolePermissionList = rolePermissionService.queryAll(new RolePermission() {{
				setRoleId(Long.valueOf(roleId));
				setPermissionId(permission.getParentId());
			}});
			if (CollectionUtils.isEmpty(rolePermissionList)){
				rolePermissionService.add(new RolePermission(){{
					setPermissionId(permission.getParentId());
					setRoleId(Long.valueOf(roleId));
				}},false);
			}
			if (permission.getParentId() != 0){
				//证明还有父级
				Permission permission1 = this.queryById(permission.getParentId());
				List<RolePermission> rolePermissionList1 = rolePermissionService.queryAll(new RolePermission() {{
					setRoleId(Long.valueOf(roleId));
					setPermissionId(permission1.getParentId());
				}});
				if (CollectionUtils.isEmpty(rolePermissionList1)){
					rolePermissionService.add(new RolePermission(){{
						setPermissionId(permission1.getParentId());
						setRoleId(Long.valueOf(roleId));
					}},false);
				}
			}
		}else{
			//删除
			rolePermissionService.remove(rolePermissions.get(0).getId());
			//是否有同级菜单 没有删除父级

			//查询同级菜单
			Permission permission = this.queryById(Long.valueOf(permissionId));
			List<Permission> permissions = this.queryAll(new Permission() {{
				setParentId(permission.getParentId());
			}});

			Boolean boo = false;
			for (Permission permission1:permissions) {
				List<RolePermission> rolePermissionList = rolePermissionService.queryAll(new RolePermission() {{
					setRoleId(Long.valueOf(roleId));
					setPermissionId(permission1.getId());
				}});
				if (CollectionUtils.isNotEmpty(rolePermissionList)){
					boo = true;
					break;
				}
			}
			if (boo){
				//没有同级的菜单 ,. 删除父级
				List<RolePermission> rolePermissions1 = rolePermissionService.queryAll(new RolePermission() {{
					setPermissionId(permission.getParentId());
					setRoleId(Long.valueOf(roleId));
				}});
				if (CollectionUtils.isNotEmpty(rolePermissions1)){
					rolePermissionService.remove(rolePermissions1.get(0).getId());
					Permission permission1 = this.queryById(permission.getParentId());
					if (permission1.getParentId().toString().equals("0")){
							//没有父级 .
							return true;
					}
					//还有父级 . 查看同级菜单是否还有权限 ., 没有权限删除父级
					List<RolePermission> rolePermissionsList = rolePermissionService.queryAll(new RolePermission() {{
						setPermissionId(permission1.getParentId());
						setRoleId(Long.valueOf(roleId));
					}});
					if (CollectionUtils.isEmpty(rolePermissionsList)){
						//删除父级
						rolePermissionService.remove(rolePermissionsList.get(0).getId());
					}
				}
			}
		}
		return true;
	}

	/**
	 * 获取子节点
	 * @param id 父节点id
	 * @param allMenu 所有菜单列表
	 * @return 每个根节点下，所有子菜单列表
	 */
	public Map<String,List<Permission>> getChild(Long id,List<Permission> allMenu,List<Long> menuIds){
		//子菜单
		List<Permission> childList = new ArrayList<Permission>();
		for (Permission nav : allMenu) {
			// 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
			//相等说明：为该根节点的子节点。
			if(nav.getParentId().equals(id)){
				if (menuIds.contains(nav.getId())){
					nav.setChecked(true);
				}else{
					nav.setChecked(false);
				}
				childList.add(nav);
			}
		}
		//递归
		for (Permission nav : childList) {
			nav.setChildren(getChild(nav.getId(), allMenu,menuIds).get("menuList"));
		}
		Collections.sort(childList,order());//排序
		//如果节点下没有子节点，返回一个空List（递归退出）
		if(childList.size() == 0 && childList.size() == 0){
			return new HashMap<>();
		}
		return new HashMap<String, List<Permission>>(){{
			put("menuList",childList);
		}};
	}


	/*
	 * 排序,根据order排序
	 */
	public Comparator<Permission> order(){
		Comparator<Permission> comparator = new Comparator<Permission>() {
			@Override
			public int compare(Permission o1, Permission o2) {
				if(o1.getId() != o2.getId()){
					return (int) (o1.getId() - o2.getId());
				}
				return 0;
			}
		};
		return comparator;
	}

}
